import React, { useState, useEffect } from 'react';
import { Dimensions, FlatList, StyleSheet, TouchableOpacity, Text, Button, View, Image, ImageBackground, ScrollView, ToastAndroid, TextInput } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { AntDesign } from '@expo/vector-icons';
import { Entypo } from '@expo/vector-icons';
import { EvilIcons } from '@expo/vector-icons';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { getNews } from '../../api/news'
import moment from 'moment';
import axios from '../../api/axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useAuth, baseURL } from '../../context/AuthProvider';
import { useFocusEffect } from '@react-navigation/native';
const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                ...style
            }
        }>
            <Text style={{ color: color ? color : '#fff' }}>{children}</Text>
        </TouchableOpacity>
    )
}
const { width, height } = Dimensions.get('window');
const MineNews = ({ navigation }) => {
    const [list, setList] = useState([]);
    const { user } = useAuth();
    // 添加动态
    const addNews = () => {
        navigation.navigate('addNews');
    };
    // 跳转话题页
    const toTopic = (e) => {
        navigation.navigate('topic', {
            cropsid: e
        });
    };
    // 更多话题
    const moreTopics = () => {
        navigation.navigate('moreTopics')
    };
    // 跳转评论页
    const newsComment = (e) => {
        navigation.navigate('newsComment', {
            newsid: e
        });
        console.log(e);
    };
    useEffect(() => {
        AsyncStorage.getItem('news').then(
            data => {
                if (data) {
                    setList(JSON.parse(data))
                }
            }
        )
        getNews().then(res => {
            AsyncStorage.setItem('news', JSON.stringify(res))
            setList(res)
        }).catch(e => {
            console.log('出错了', e);
        });
    }, [])
    // 返回刷新页面
    useFocusEffect(React.useCallback(() => {
        AsyncStorage.getItem('news').then(
            data => {
                if (data) {
                    setList(JSON.parse(data))
                }
            }
        )
        getNews().then(res => {
            AsyncStorage.setItem('news', JSON.stringify(res))
            setList(res);
        }).catch(e => {
            console.log('出错了', e);
        });
    }, []))
    // 头部组件
    const Header = () => (
        <View style={{ alignItems: 'center', backgroundColor: '#f7f8fa' }}>
            <ImageBackground style={{ flex: 1, width: width * 1, minHeight: 352, borderRadius: 8, alignItems: 'center' }}
                source={require('../../../images/news/bg5.jpg')} >
                <View
                    style={{
                        width: '94%',
                        // backgroundColor: '#CBF2CB',
                        minHeight: 280,
                        borderRadius: 8,
                        top: 12,
                    }} >
                    <View style={{
                        height: 88,
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'space-between'
                    }}>
                        <View>
                            <Text
                                style={{
                                    color: '#0D3A2C',
                                    fontSize: 19,
                                    // left: 25,
                                }}
                            >大家都在聊</Text>
                        </View>
                        <View>
                            <Ionicons
                                name="add-circle-outline"
                                size={36}
                                color="#04543f"
                                onPress={addNews}
                                style={{
                                    marginBottom: 15,
                                    marginLeft: 10
                                }}
                            />
                            <Text
                                onPress={moreTopics}
                                style={{
                                    color: '#716F6D',
                                    marginTop: 12,
                                    marginRight: 10
                                    // left: 272,
                                    // top: 26
                                }}
                            >更多{'>'}</Text>
                        </View>
                    </View>
                    <View style={{ alignItems: 'center' }}>
                        <ImageBackground style={{
                            width: width * 0.92, height: 163,
                            marginTop: 5, opacity: 1, borderRadius: 26, overflow: 'hidden',
                            borderBottomLeftRadius: 10, borderTopRightRadius: 10
                        }}
                            source={require('../../../images/news/bg1.jpg')} >
                            <View style={{
                                height: 58,
                                flexDirection: 'row',
                                alignItems: 'center',
                                justifyContent: 'space-between'
                            }}>
                                <View>
                                    <Text style={{
                                        marginLeft: 10,
                                        fontSize: 21,
                                        color: '#FDF194'
                                    }}>#郁金香</Text>
                                </View>
                                <View
                                    style={{
                                        width: 95,
                                        height: 40,
                                        backgroundColor: '#rgba(253,241,148,0.8)',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        borderRadius: 12,
                                        marginRight: 7,
                                        marginTop: 100,
                                    }}>
                                    <Text
                                        onPress={() => toTopic(9)}
                                        style={{ color: '#2A5F6b', }}
                                    >进入指南{'>>'}</Text>
                                </View>
                            </View>
                        </ImageBackground>
                    </View>
                    <View style={{ flexDirection: 'row', height: height * 0.131, justifyContent: 'space-around', marginTop: 10 }}>
                        <View onStartShouldSetResponder={() => toTopic(5)}>
                            <ImageBackground style={{ width: width * 0.14, height: width * 0.19, top: 4, alignItems: 'center', justifyContent: 'flex-end' }}
                                source={require('../../../images/news/1.png')}>
                                <Text style={{ top: 3, color: '#2A5F69' }}>草莓</Text>
                            </ImageBackground>
                        </View>
                        <View onStartShouldSetResponder={() => toTopic(6)} style={{ alignItems: 'center', paddingTop: 5 }}>
                            <Image style={{ width: width * 0.125, height: width * 0.145, }}
                                source={require('../../../images/news/604.png')} >
                            </Image>
                            <Text style={{ marginTop: 2, color: '#2A5F69' }}>油菜</Text>
                        </View>
                        <View onStartShouldSetResponder={() => toTopic(1)}>
                            <ImageBackground style={{ width: width * 0.14, height: width * 0.18, alignItems: 'center', justifyContent: 'flex-end' }}
                                source={require('../../../images/news/3.png')} >
                                <Text style={{ top: 11, color: '#2A5F69' }}>柠檬</Text>
                            </ImageBackground>
                        </View>
                        <View onStartShouldSetResponder={() => toTopic(8)}>
                            <ImageBackground style={{ width: width * 0.15, height: width * 0.17, alignItems: 'center', justifyContent: 'flex-end' }}
                                source={require('../../../images/news/4.png')} >
                                <Text style={{ top: 15, color: '#2A5F69' }}>玫瑰</Text>
                            </ImageBackground>
                        </View>
                    </View>
                </View>
            </ImageBackground>
            <View style={{
                width: width,
                height: 55,
                justifyContent: 'center',
                borderTopLeftRadius: 20,
                borderTopRightRadius: 10,
            }}>
                <Text style={{
                    lineHeight: 40, height: 40, fontSize: 20,
                    fontWeight: 'bold', color: '#2A5F6b', borderLeftWidth: 3,
                    borderLeftColor: '#42C05C', paddingLeft: 10,
                    marginLeft: 7
                }}>动态广场</Text>
            </View>
        </View>
    )
    // 删除动态
    const deleteNews = (id) => {
        console.log(id);
        axios.post('/news/deletenews', {
            newsid: id
        }).then(res => {
            console.log(res);
            if (res.code == 200) {
                // 刷新动态
                AsyncStorage.getItem('news').then(
                    data => {
                        if (data) {
                            setList(JSON.parse(data))
                        }
                    }
                )
                getNews().then(res => {
                    AsyncStorage.setItem('news', JSON.stringify(res))
                    setList(res);
                }).catch(e => {
                    console.log('出错了', e);
                });
                ToastAndroid.show("删除成功", 2000);
            }
        })
    }
    return (
        <View style={{ alignItems: 'center' }}>
            {/* 动态列表模块 */}
            <View >
                <FlatList
                    // onRefresh={onRefresh}
                    // refreshing={refreshing}
                    data={list}
                    ListHeaderComponent={Header}
                    renderItem={({ item }) => {
                        return (
                            <View style={{
                                minHeight: 150,
                                backgroundColor: '#FFFFFF',
                                marginBottom: 5,
                                alignItems: 'center'
                            }}>
                                <View style={{
                                    width: width, height: 70,
                                    flexDirection: 'row',
                                    paddingLeft: 20,
                                    backgroundColor: 'rgba(203,242,203,0.7)',
                                    alignItems: 'center',
                                    justifyContent: 'space-between'
                                }}>
                                    <View style={{ alignItems: 'center', flexDirection: 'row', }}>
                                        {item.avatar ?
                                            <Image style={{ width: 60, height: 60, borderRadius: 30 }} source={{ uri: baseURL + item.avatar }} />
                                            :
                                            <Image style={{ width: 60, height: 60, borderRadius: 30 }} source={require('../../../images/mine/1.jpg')} />
                                        }
                                        <View style={{ paddingLeft: 15 }}>
                                            <Text style={{ fontSize: 15.5 }}>{item.nickname}</Text>
                                            <Text style={{ fontSize: 13, color: '#bbb' }}>{moment(item.addtime).format("YYYY-MM-DD HH:mm")}</Text>
                                        </View>
                                    </View>
                                    <View style={item.userid == user.userid ? { marginRight: '5%' } : { display: 'none' }}>
                                        <AntDesign name="delete" size={24} color="#2A5F6b" onPress={() => deleteNews(item.newsid)} />
                                    </View>
                                </View>
                                <View style={{ alignItems: 'center' }}>
                                    <View style={{ width: width * 0.8, marginTop: 15, }}>
                                        <Text>{item.newstext}</Text>
                                        {
                                            item.newsimg ?
                                                <View style={item.newsimg ? { flexDirection: 'row', marginTop: 10, } : { display: 'none' }}>
                                                    {
                                                        item.newsimg.map((item1) => {
                                                            return <Image key={item1.newsimgid} style={{ width: 110, height: 110, marginRight: 10 }} source={{ uri: baseURL + item1.newsimgs }} />
                                                        })
                                                    }
                                                </View>
                                                : <></>
                                        }
                                        <View style={{
                                            marginTop: 5,
                                            marginBottom: 2,
                                            backgroundColor: 'rgba(203,242,203,0.8)',
                                            height: 25, width: 55,
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            borderRadius: 13
                                        }}>
                                            <Text style={{ color: '#2A5F6b' }}>#{item.cropname}</Text>
                                        </View>
                                    </View>
                                </View>
                                <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
                                    {/* 评论 */}
                                    <View
                                        style={{ flexDirection: 'row', height: 35, alignItems: 'center', marginTop: 7, marginBottom: 4 }}
                                        onStartShouldSetResponder={() => newsComment(item.newsid)}>
                                        {/* <MaterialCommunityIcons name="comment-processing-outline" size={28} color="black" /> */}
                                        <Image source={{ uri: baseURL + user.avatar }} style={{ width: 32, height: 32, borderRadius: 15, marginLeft: '3%', }}></Image>
                                        <TextInput
                                            style={styles.input}
                                            placeholder="说点什么吧……"
                                            editable={false}
                                        />
                                    </View>
                                </View>
                            </View>
                        )
                    }
                    }
                // onEndReached={onEnd}
                // keyExtractor={item => item.id}
                />
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    // container: {
    //     marginHorizontal: 15
    // },
    input: {
        width: '85%',
        height: 28,
        lineHeight: 28,
        color: '#2A5F69',
        paddingLeft: 8,
        fontSize: 15,
        backgroundColor: 'rgba(203,242,203,0.2)',
        marginLeft: 5,
        borderRadius:7
    },
});

export default MineNews;

